package com.xianxing.gateway.log.service.impl;

import com.xianxing.gateway.log.dao.RequestLogMapper;
import com.xianxing.gateway.log.pojo.RequestLog;
import com.xianxing.gateway.log.service.RequestLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * 网关服务实现类
 * @author 唐保罗
 * @version 1.0
 */
@Service
public class RequestLogServiceImpl implements RequestLogService {

    @Autowired
    private RequestLogMapper requestLogMapper;

    @Override
    public void addAccessLog(HttpServletRequest request){
        RequestLog requestLog = new RequestLog();
        requestLog.setRequest_id(UUID.randomUUID().toString());
        requestLog.setRequest_method(request.getMethod());
        requestLog.setRequest_time(System.currentTimeMillis());
        requestLog.setRequest_url(request.getRequestURL().toString());
        requestLog.setRequest_risk_level(this.defineRiskLevel(request.getMethod()));
        int i = requestLogMapper.insertSelective(requestLog);
        if (i<=0){
            throw new RuntimeException("添加访问日志异常");
        }
    }

    private String defineRiskLevel(String method){
        if (method.equals("DELETE")){
            return "danger";
        }else if (method.equals("PUT")){
            return "middle";
        }else if (method.equals("POST")||method.equals("GET")){
            return "low";
        } else {
            return "un define";
        }
    }

}
